#include "treeview.h"
#include <QApplication>
#include <QDrag>
#include <QDragMoveEvent>
#include <QMimeData>
#include <QStandardItemModel>
#include "thumbnail.h"
#include <QDebug>
#include <QVariant>
TreeView::TreeView(QWidget *parent) : QTreeView(parent)
{
    setAcceptDrops(true);
    connect(this,&QTreeView::pressed,this,[=](const QModelIndex &index)
    {
        pressIndex = index;
    });
    setStyleSheet("border: none;");
}
void TreeView::mousePressEvent(QMouseEvent *event)
{
    QTreeView::mousePressEvent(event);
    if(event->buttons() & Qt::LeftButton){
        startPos = event->pos();
    }
}

void TreeView::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton){
        if((event->pos() - startPos).manhattanLength() < QApplication::startDragDistance()) return;
        resizeColumnToContents(pressIndex.row());

        QString text = model()->itemData(pressIndex).value(0).toString();
        QIcon icon = model()->itemData(pressIndex).value(1).value<QIcon>();
        if(icon.isNull())
        {
            return;
        }
        QByteArray itemData;
        QDataStream dataStream(&itemData, QIODevice::WriteOnly);
        dataStream << pressIndex.data(Qt::UserRole+1).toInt();

        QMimeData *mimeData = new QMimeData;
        mimeData->setData(myMimeType(), itemData);
//[1]

//[2]设置拖拽时的缩略图
        thumbnail *DragImage = new thumbnail(this);
        DragImage->setupthumbnail(icon, text);
        //DragImage->setIconSize(18);  //default:20
        QPixmap pixmap = DragImage->grab();

        QDrag *drag = new QDrag(this);
        drag->setMimeData(mimeData);
        drag->setPixmap(pixmap);
        drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));
//[2]

        //删除的行需要根据theInsertRow和theDragRow的大小关系来判断(这个也是我根据实际情况测试发现的)
        if(drag->exec(Qt::MoveAction) == Qt::MoveAction){
        }
    }
}

void TreeView::dragEnterEvent(QDragEnterEvent *event)
{
    TreeView *source = qobject_cast<TreeView *>(event->source());
    if (source && source == this) {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}

void TreeView::dragLeaveEvent(QDragLeaveEvent *event)
{

//    theInsertRow = -1;
    event->accept();
}

void TreeView::dragMoveEvent(QDragMoveEvent *event)
{
    TreeView *source = qobject_cast<TreeView *>(event->source());
    if (source && source == this) {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}
